﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Honestysoft.Financing.Model;
using System.Data;
using Honestysoft.Financing.DataAccess;
using System.Data.Common;
using Honestysoft.BaseObject;
using Honestysoft.DictionaryHelper;

namespace Honestysoft.Financing.BusinessLogic
{
    public class Project
    {
        string _connectionStringName;
        /// <summary>
        /// 构造函数，使用指定的连接字符串
        /// </summary>
        /// <param name="connectionStringName">连接字符串名称</param>
        public Project(string connectionStringName)
        {
            _connectionStringName = connectionStringName;
        }
        ///// <summary>
        ///// 得到下一个项目排序号
        ///// </summary>
        ///// <returns></returns>
        //public int GetNextProjectSortCode()
        //{
        //    return new BD_Project_DAL(_connectionStringName).GetNextSortCode();
        //}
        /// <summary>
        /// 得到所有的拆分项目
        /// </summary>
        /// <returns></returns>
        public DataTable GetSplitProject()
        {
            return new BD_ProjectSplit_Detail_DAL(_connectionStringName).GetSplitProject();
        }
        /// <summary>
        /// 得到可选择的拆分项目
        /// </summary>
        /// <param name="projectCategory"></param>
        /// <param name="code"></param>
        /// <param name="sn"></param>
        /// <param name="name"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetSelectSplitProject(string projectCategory,string code,string sn,string name, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            return new BD_Project_DAL(_connectionStringName).GetSelectSplitProject(projectCategory,code,sn,name, pageSize, currentPageIndex, out pageCount, out recordCount);
        }

        public bool CreateProjectSplit(string[] arrId)
        {
            bool bRet = false;
            BD_ProjectSplit projSplit = new BD_ProjectSplit();
            List<BD_ProjectSplit_Detail> lsDetail = new List<BD_ProjectSplit_Detail>();
            BD_ProjectSplit_Detail item = null;
            projSplit.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
            foreach (string id in arrId)
            {
                item = new BD_ProjectSplit_Detail();
                item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                item.ProjectID = id;
                item.SplitID = projSplit.ID;
                lsDetail.Add(item);
            }
            DbTransaction transaction = Honestysoft.BaseLibrary.Data.DatabaseProvider.GetDbTransaction(_connectionStringName);
            DbConnection connection = transaction.Connection;
            try
            {
                new BD_ProjectSplit_DAL(_connectionStringName).InsertEntity(projSplit, transaction);
                new BD_ProjectSplit_Detail_DAL(_connectionStringName).InsertEntitys(lsDetail, transaction);
                transaction.Commit();
                bRet = true;
            }
            catch(Exception ex)
            {
                transaction.Rollback();
                Honestysoft.BaseLibrary.Logging.LoggingHelper.WriteLog(ex.Message);
                Honestysoft.BaseLibrary.ExceptionHandling.ExceptionHelper.ExceptionDistribute(ex, false);
            }
            finally
            {
                connection.Close();
            }
            return bRet;
        }
        /// <summary>
        /// 添加项目拆分
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="splitId"></param>
        /// <returns></returns>
        public bool AddProjectSplit(string[] arrProjectId, string splitId)
        {
            List<BD_ProjectSplit_Detail> lsDetail = new List<BD_ProjectSplit_Detail>();
            BD_ProjectSplit_Detail item = null;
            foreach (string s in arrProjectId)
            {
                item = new BD_ProjectSplit_Detail();
                item.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                item.ProjectID = s;
                item.SplitID = splitId;
                lsDetail.Add(item);
            }
            return new BD_ProjectSplit_Detail_DAL(_connectionStringName).InsertEntitys(lsDetail) == arrProjectId.Length;
        }

        /// <summary>
        /// 得到项目名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetProjectName(string id)
        {
            return new BD_Project_DAL(_connectionStringName).SelectEntityByKey(id).Name;
        }

        /// <summary>
        /// 得到项目分类的项目数量
        /// </summary>
        /// <returns></returns>
        public DataTable GetProjectCategoryCount(bool? isInit)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectCategoryCount(isInit);
        }
        /// <summary>
        /// 根据项目类别得到项目
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public DataTable GetProjectsByCategory(string category, bool? isInit)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectsByCategory(category, isInit);
        }

        /// <summary>
        /// 得到项目参建单位
        /// </summary>
        /// <param name="projectId">项目标识</param>
        /// <param name="projectCategory">项目类别</param>
        /// <param name="projectName">项目名称</param>
        /// <param name="unitType">单位类型</param>
        /// <param name="compName">单位名称</param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectCompany(string projectId,string projectCategory, string projectName, EnumItem.UnitType? unitType, string compName, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            return new BD_ProjectCompany_DAL(_connectionStringName).GetProjectCompany(projectId, projectCategory,projectName, unitType, compName, pageSize, currentPageIndex, out pageCount, out recordCount);
        }
        /// <summary>
        /// 得到项目概算变动情况
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectBudget(string projectId, string projectName, string projectCategory, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_ProjectBudget_DAL(_connectionStringName).GetProjectBudget(projectId, projectName, projectCategory, pageSize, currentPageIndex, out pageCount, out recordCount);
            dt.Columns.Add("IsResult", typeof(bool));
            string id = "";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["ProjectID"].ToString() != id)
                {
                    id = dr["ProjectID"].ToString();
                    dr["IsResult"] = true;
                }
                else
                {
                    dr["IsResult"] = false;
                }
            }
            return dt;
        }
        /// <summary>
        /// 得到项目年度投资计划
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="year"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectInvestmentPlan(string projectId, string projectName, string projectCategory, int? year, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_ProjectInvestmentPlan_DAL(_connectionStringName).GetProjectInvestmentPlan(projectId, projectName, projectCategory, year, pageSize, currentPageIndex, out pageCount, out recordCount);
            dt.Columns.Add("IsResult", typeof(bool));
            string id = "";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["ProjectID"].ToString() != id)
                {
                    id = dr["ProjectID"].ToString();
                    dr["IsResult"] = true;
                }
                else
                {
                    dr["IsResult"] = false;
                }
            }
            return dt;
        }
        /// <summary>
        /// 得到项目贷款额度
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="year"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectLoanAmount(string projectId, string projectName, string projectCategory, int? year, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_ProjectLoanAmount_DAL(_connectionStringName).GetProjectLoanAmount(projectId, projectName, projectCategory, year, pageSize, currentPageIndex, out pageCount, out recordCount);
            dt.Columns.Add("IsResult", typeof(bool));
            string id = "";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["ProjectID"].ToString() != id)
                {
                    id = dr["ProjectID"].ToString();
                    dr["IsResult"] = true;
                }
                else
                {
                    dr["IsResult"] = false;
                }
            }
            return dt;
        }
        /// <summary>
        /// 得到国开行贷款额度
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="year"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectGKLoanAmount(string projectId, string projectName, string projectCategory, int? year, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_ProjectGKLoanAmount_DAL(_connectionStringName).GetProjectGKLoanAmount(projectId, projectName, projectCategory, year, pageSize, currentPageIndex, out pageCount, out recordCount);
            dt.Columns.Add("IsResult", typeof(bool));
            string id = "";
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["ProjectID"].ToString() != id)
                {
                    id = dr["ProjectID"].ToString();
                    dr["IsResult"] = true;
                }
                else
                {
                    dr["IsResult"] = false;
                }
            }
            return dt;
        }

        /// <summary>
        /// 得到国开行贷款额度
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="year"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectAddInvestment(string projectId, string projectName, string projectCategory, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_ProjectAddInvestment_DAL(_connectionStringName).GetProjectAddInvestment(projectId, projectName, projectCategory, pageSize, currentPageIndex, out pageCount, out recordCount);
            //dt.Columns.Add("IsResult", typeof(bool));
            //string id = "";
            //foreach (DataRow dr in dt.Rows)
            //{
            //    if (dr["ProjectID"].ToString() != id)
            //    {
            //        id = dr["ProjectID"].ToString();
            //        dr["IsResult"] = true;
            //    }
            //    else
            //    {
            //        dr["IsResult"] = false;
            //    }
            //}
            return dt;
        }
        /// <summary>
        /// 得到项目信息完整性
        /// </summary>
        /// <param name="projectName"></param>
        /// <param name="projectCategory"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetProjectComplete(string projectName,string projectCategory, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            DataTable dt = new BD_Project_DAL(_connectionStringName).GetProjectComplete(projectName, projectCategory, pageSize, currentPageIndex, out pageCount, out recordCount);
            return dt;
        }
        /// <summary>
        /// 得到项目当前活动的各项数据（项目概算、年度投资计划，国开行贷款额度，项目贷款额度）
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ProjectActiveData GetProjectActiveData(string projectId)
        {
            DataTable dt = new BD_Project_DAL(_connectionStringName).GetProjectActiveData(projectId);
            if (dt == null || dt.Rows.Count != 1)
            {
                return null;
            }
            ProjectActiveData item = new ProjectActiveData();
            //    Select ID,Name,
            //@gsAmount As GSAmount,@gsDate As GSDate,
            //@planYear As PlanYear,@planAmount As PlanAmount,
            //@gkYear As GKYear,@gkAmount As GKAmount,
            //@projYear As ProjectYear,@projAmount As ProjectAmount
            item.GKAmount = Convert.ToDecimal(dt.Rows[0]["GKAmount"]);
            item.GKYear = Convert.ToInt32(dt.Rows[0]["GKYear"]);
            item.GSAmount = Convert.ToDecimal(dt.Rows[0]["GSAmount"]);
            if (!dt.Rows[0].IsNull("GSDate"))
            {
                item.GSDate = Convert.ToDateTime(dt.Rows[0]["GSDate"]);
            }
            item.PlanAmount = Convert.ToDecimal(dt.Rows[0]["PlanAmount"]);
            item.PlanYear = Convert.ToInt32(dt.Rows[0]["PlanYear"]);
            item.ProjectAmount = Convert.ToDecimal(dt.Rows[0]["ProjectAmount"]);
            item.ProjectID = projectId;
            item.ProjectName = dt.Rows[0]["Name"].ToString();
            item.ProjectYear = Convert.ToInt32(dt.Rows[0]["ProjectYear"]);
            return item;
        }

        /// <summary>
        /// 得到项目基本信息(不包括年度投资计划等)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BD_Project GetBaseProject(string id)
        {
            BD_Project project = new BD_Project_DAL(_connectionStringName).SelectEntityByKey(id);
            List<string> lsCompID = new List<string>();
            lsCompID.Add(project.Owner971);
            lsCompID.Add(project.Owner);
            DataTable dtComp = new Reports_DAL(_connectionStringName).GetCompanyName(lsCompID.ToArray());
            DataRow[] rows = dtComp.Select("ID='" + project.Owner971 + "'");
            if (rows != null && rows.Length == 1)
            {
                project.Owner971Name = rows[0]["CompName"].ToString();
            }
            rows = dtComp.Select("ID='" + project.Owner + "'");
            if (rows != null && rows.Length == 1)
            {
                project.OwnerName = rows[0]["CompName"].ToString();
            }
            return project;
        }

        /// <summary>
        /// 得到项目的全部信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public BD_Project GetFullProject(string id)
        {
            BD_Project project = new BD_Project_DAL(_connectionStringName).SelectEntityByKey(id);
            List<string> lsCompID = new List<string>();
            lsCompID.Add(project.Owner971);
            lsCompID.Add(project.Owner);
            if (!string.IsNullOrEmpty(project.DOwner)) { lsCompID.Add(project.DOwner); }
            DataTable dtComp = new Reports_DAL(_connectionStringName).GetCompanyName(lsCompID.ToArray());
            DataRow[] rows = dtComp.Select("ID='" + project.Owner971 + "'");
            if (rows != null && rows.Length == 1)
            {
                project.Owner971Name = rows[0]["CompName"].ToString();
            }
            rows = dtComp.Select("ID='" + project.Owner + "'");
            if (rows != null && rows.Length == 1)
            {
                project.OwnerName = rows[0]["CompName"].ToString();
            }
            rows = dtComp.Select("ID='" + project.DOwner + "'");
            if (rows != null && rows.Length == 1)
            {
                project.DOwnerName = rows[0]["CompName"].ToString();
            }
            QueryParameters queryParameter = new QueryParameters();
            queryParameter.Add("ProjectID", id, QueryParameters.OperatorType.Equal);
            OrderParameters orderParameter = new OrderParameters();
            //orderParameter.Add("AddDate", OrderParameters.OrderDirection.Desc);
            //orderParameter.Add("CreateTime", OrderParameters.OrderDirection.Desc);
            //project.AddInvesments = new BaseBusinessLogic<BD_ProjectAddInvestment>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            orderParameter = new OrderParameters();//changeDate Desc,CreateTime Desc
            orderParameter.Add("changeDate", OrderParameters.OrderDirection.Desc);
            orderParameter.Add("CreateTime", OrderParameters.OrderDirection.Desc);
            project.Budgets = new BaseBusinessLogic<BD_ProjectBudget>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            orderParameter = new OrderParameters();//TheYear Desc,CreateTime Desc
            orderParameter.Add("TheYear", OrderParameters.OrderDirection.Desc);
            orderParameter.Add("CreateTime", OrderParameters.OrderDirection.Desc);
            project.GKLoanAmounts = new BaseBusinessLogic<BD_ProjectGKLoanAmount>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            project.LoanAmounts = new BaseBusinessLogic<BD_ProjectLoanAmount>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            orderParameter = new OrderParameters();//PlanYear Desc,CreateTime Desc
            orderParameter.Add("PlanYear", OrderParameters.OrderDirection.Desc);
            orderParameter.Add("CreateTime", OrderParameters.OrderDirection.Desc);
            project.YearPlans = new BaseBusinessLogic<BD_ProjectInvestmentPlan>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            orderParameter = new OrderParameters();
            orderParameter.Add("CreateTime", OrderParameters.OrderDirection.Desc);
            project.ZBJChanges = new BaseBusinessLogic<BD_ProjectZBJChange>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            orderParameter = new OrderParameters();
            orderParameter.Add("SortCode");
            project.Companys = new BaseBusinessLogic<BD_ProjectCompany>(_connectionStringName).GetEntitys(queryParameter, orderParameter);
            return project;
        }

        /// <summary>
        /// 确认初始化项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="userId"></param>
        /// <param name="opinion"></param>
        /// <returns></returns>
        public bool ConfirmInit(string projectId,string userId, string opinion)
        {
            return new BD_Project_DAL(_connectionStringName).ConfirmInit(projectId, userId, opinion);
        }

        /// <summary>
        /// 根据项目代码的到项目
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public DataTable GetProjectByCode(string code)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectByCode(code);
        }
        /// <summary>
        /// 根据项目编号得到项目
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        public DataTable GetProjectBySN(string sn)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectBySN(sn);
        }
        /// <summary>
        /// 查找项目信息
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="owner971"></param>
        /// <param name="name"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable QueryProjects(string sn, string category, string name, int pageSize, int currentPageIndex, out int recordCount)
        {
            return new BD_Project_DAL(_connectionStringName).QueryProjects(sn, category, name, pageSize, currentPageIndex, out recordCount);
        }

        /// <summary>
        /// 保存项目信息
        /// </summary>
        /// <param name="project"></param>
        /// <param name="transaction"></param>
        /// <returns></returns>
        public bool SaveProject(BD_Project project,DbTransaction transaction)
        {
            if (string.IsNullOrEmpty(project.ProjectCategory))
            {
                project.ProjectCategory = GetProjectCategoryByOwner971(project.Owner971);
            }
            if (project.SortCode == 0)
            {
                project.SortCode = GetProjectSortCodeBySN(project.SN);
            }
            BD_Project_DAL dal1 = new BD_Project_DAL(_connectionStringName);
            BD_ProjectAddInvestment_DAL dal2 = new BD_ProjectAddInvestment_DAL(_connectionStringName);
            BD_ProjectBudget_DAL dal3 = new BD_ProjectBudget_DAL(_connectionStringName);
            BD_ProjectGKLoanAmount_DAL dal4 = new BD_ProjectGKLoanAmount_DAL(_connectionStringName);
            BD_ProjectInvestmentPlan_DAL dal5 = new BD_ProjectInvestmentPlan_DAL(_connectionStringName);
            BD_ProjectLoanAmount_DAL dal6 = new BD_ProjectLoanAmount_DAL(_connectionStringName);
            BD_ProjectZBJChange_DAL dal7 = new BD_ProjectZBJChange_DAL(_connectionStringName);
            BD_ProjectCompany_DAL dal8 = new BD_ProjectCompany_DAL(_connectionStringName);
            if (project.dataState == EnumItem.DataState.New)
            {
                dal1.InsertEntity(project, transaction);
                if (project.AddInvesments != null && project.AddInvesments.Count > 0)
                {
                    project.AddInvesments = project.AddInvesments.FindAll((BD_ProjectAddInvestment find) => find.dataState != EnumItem.DataState.Delete);
                    if (project.AddInvesments != null && project.AddInvesments.Count > 0)
                    {
                        foreach (BD_ProjectAddInvestment item in project.AddInvesments)
                        {
                            item.ProjectID = project.ID;
                        }
                        dal2.InsertEntitys(project.AddInvesments, transaction);
                    }
                }
                if (project.Budgets != null && project.Budgets.Count > 0)
                {
                    foreach (BD_ProjectBudget item in project.Budgets)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal3.InsertEntitys(project.Budgets, transaction);
                }
                if (project.GKLoanAmounts != null && project.GKLoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectGKLoanAmount item in project.GKLoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal4.InsertEntitys(project.GKLoanAmounts, transaction);
                }
                if (project.YearPlans != null && project.YearPlans.Count > 0)
                {
                    foreach (BD_ProjectInvestmentPlan item in project.YearPlans)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal5.InsertEntitys(project.YearPlans, transaction);
                }
                if (project.LoanAmounts != null && project.LoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectLoanAmount item in project.LoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal6.InsertEntitys(project.LoanAmounts, transaction);
                }
                if (project.Companys != null && project.Companys.Count > 0)
                {
                    foreach (BD_ProjectCompany item in project.Companys)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal8.InsertEntitys(project.Companys, transaction);
                }
            }
            else
            {
                dal1.UpdateEntity(project, transaction);
                if (project.ZBJChanges != null && project.ZBJChanges.Count > 0)
                {
                    List<BD_ProjectZBJChange> lsInsertZBJChange = new List<BD_ProjectZBJChange>();
                    foreach (BD_ProjectZBJChange item in project.ZBJChanges)
                    {
                        item.ProjectID = project.ID;
                        if (item.dataState == EnumItem.DataState.New)
                        {
                            lsInsertZBJChange.Add(item);
                        }
                    }
                    if (lsInsertZBJChange.Count > 0)
                    {
                        dal7.InsertEntitys(lsInsertZBJChange, transaction);
                    }
                }
                if (project.AddInvesments != null && project.AddInvesments.Count > 0)
                {
                    foreach (BD_ProjectAddInvestment item in project.AddInvesments)
                    {
                        item.ProjectID = project.ID;
                    }
                    List<BD_ProjectAddInvestment> lsInsertAddZBJ = new List<BD_ProjectAddInvestment>();
                    List<BD_ProjectAddInvestment> lsUpdateAddZBJ = new List<BD_ProjectAddInvestment>();
                    List<string> lsDeleteAddZBJ = new List<string>();
                    foreach (BD_ProjectAddInvestment item in project.AddInvesments)
                    {
                        if (item.dataState == EnumItem.DataState.Delete)
                        {
                            lsDeleteAddZBJ.Add(item.ID);
                        }
                        else if (item.dataState == EnumItem.DataState.Modify)
                        {
                            lsUpdateAddZBJ.Add(item);
                        }
                        else if (item.dataState == EnumItem.DataState.New)
                        {
                            lsInsertAddZBJ.Add(item);
                        }
                    }
                    if (lsDeleteAddZBJ.Count > 0)
                    {
                        dal2.DeleteByKey(lsDeleteAddZBJ.ToArray(), transaction);
                    }
                    if (lsInsertAddZBJ.Count > 0)
                    {
                        dal2.InsertEntitys(lsInsertAddZBJ, transaction);
                    }
                    if (lsUpdateAddZBJ.Count > 0)
                    {
                        dal2.UpdateEntitys(lsUpdateAddZBJ, transaction);
                    }
                }
                if (project.Budgets != null && project.Budgets.Count > 0)
                {
                    foreach (BD_ProjectBudget item in project.Budgets)
                    {
                        item.ProjectID = project.ID;
                    }
                    List<BD_ProjectBudget> lsInsertBudget = project.Budgets.FindAll((BD_ProjectBudget find) => find.dataState == EnumItem.DataState.New);
                    if (lsInsertBudget != null && lsInsertBudget.Count > 0)
                    {
                        dal3.InsertEntitys(lsInsertBudget, transaction);
                    }
                }
                if (project.GKLoanAmounts != null && project.GKLoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectGKLoanAmount item in project.GKLoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    List<BD_ProjectGKLoanAmount> lsInsertGKLoan = project.GKLoanAmounts.FindAll((BD_ProjectGKLoanAmount find) => find.dataState == EnumItem.DataState.New);
                    if (lsInsertGKLoan != null && lsInsertGKLoan.Count > 0)
                    {
                        dal4.InsertEntitys(lsInsertGKLoan, transaction);
                    }
                }
                if (project.YearPlans != null && project.YearPlans.Count > 0)
                {
                    foreach (BD_ProjectInvestmentPlan item in project.YearPlans)
                    {
                        item.ProjectID = project.ID;
                    }
                    List<BD_ProjectInvestmentPlan> lsInsertPlanYear = project.YearPlans.FindAll((BD_ProjectInvestmentPlan find) => find.dataState == EnumItem.DataState.New);
                    if (lsInsertPlanYear != null && lsInsertPlanYear.Count > 0)
                    {
                        dal5.InsertEntitys(lsInsertPlanYear, transaction);
                    }
                }
                if (project.LoanAmounts != null && project.LoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectLoanAmount item in project.LoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    List<BD_ProjectLoanAmount> lsInsertProjLoan = project.LoanAmounts.FindAll((BD_ProjectLoanAmount find) => find.dataState == EnumItem.DataState.New);
                    if (lsInsertProjLoan != null && lsInsertProjLoan.Count > 0)
                    {
                        dal6.InsertEntitys(lsInsertProjLoan, transaction);
                    }
                }
                if (project.Companys != null && project.Companys.Count > 0)
                {
                    List<BD_ProjectCompany> lsInsertCompany = new List<BD_ProjectCompany>();
                    List<string> lsDeleteCompanyID = new List<string>();
                    foreach (BD_ProjectCompany item in project.Companys)
                    {
                        item.ProjectID = project.ID;
                        if (item.dataState == EnumItem.DataState.New)
                        {
                            lsInsertCompany.Add(item);
                        }
                        else if (item.dataState == EnumItem.DataState.Delete)
                        {
                            lsDeleteCompanyID.Add(item.ID);
                        }
                    }
                    if (lsDeleteCompanyID.Count > 0)
                    {
                        dal8.DeleteByKey(lsDeleteCompanyID.ToArray(), transaction);
                    }
                    if (lsInsertCompany != null && lsInsertCompany.Count > 0)
                    {
                        dal8.InsertEntitys(lsInsertCompany, transaction);
                    }
                }
                dal1.RefreshATProjectInfo(project.ID, transaction);
                //new Bu_DocReceive_Temp_DAL(_connectionStringName).UpdateProjectInfo(project, transaction);
                //new Bu_AuditTable_DAL(_connectionStringName).UpdateProjectInfo(project, transaction);

            }
            return true;
        }

        /// <summary>
        /// 根据项目单位得到项目类别
        /// </summary>
        /// <param name="owner971"></param>
        /// <returns></returns>
        private string GetProjectCategoryByOwner971(string owner971)
        {
            Sys_Dictionary dict = new BaseBusinessLogic<Sys_Dictionary>(_connectionStringName).GetEntity(owner971);
            if (dict != null)
            {
                return dict.DictValue;
            }
            return "";
        }
        /// <summary>
        /// 通过项目编号得到排序号
        /// </summary>
        /// <param name="sn"></param>
        /// <returns></returns>
        private int GetProjectSortCodeBySN(string sn)
        {
            if (sn.IndexOf("(") > 0)//有括号
            {
                return Convert.ToInt32(sn.Substring(0, sn.IndexOf("(")));
            }
            else
            {
                return Convert.ToInt32(sn);
            }
        }

        /// <summary>
        /// 首次申请收文回执的项目保存并入库，同时更新回执信息
        /// </summary>
        /// <param name="project"></param>
        /// <param name="docRecID"></param>
        /// <returns></returns>
        public bool ProjectToDatabase(BD_Project project,string docRecID,DbTransaction transaction)
        {
            bool bRet = false;
            try
            {
                if (string.IsNullOrEmpty(project.ProjectCategory))
                {
                    project.ProjectCategory = GetProjectCategoryByOwner971(project.Owner971);
                }
                if (project.SortCode == 0)
                {
                    project.SortCode = GetProjectSortCodeBySN(project.SN);
                }
                BD_Project_DAL dal1 = new BD_Project_DAL(_connectionStringName);
                BD_ProjectAddInvestment_DAL dal2 = new BD_ProjectAddInvestment_DAL(_connectionStringName);
                BD_ProjectBudget_DAL dal3 = new BD_ProjectBudget_DAL(_connectionStringName);
                BD_ProjectGKLoanAmount_DAL dal4 = new BD_ProjectGKLoanAmount_DAL(_connectionStringName);
                BD_ProjectInvestmentPlan_DAL dal5 = new BD_ProjectInvestmentPlan_DAL(_connectionStringName);
                BD_ProjectLoanAmount_DAL dal6 = new BD_ProjectLoanAmount_DAL(_connectionStringName);
                BD_ProjectCompany_DAL dal8 = new BD_ProjectCompany_DAL(_connectionStringName);
                dal1.InsertEntity(project, transaction);
                //如果是拆分项目，要检测是否有拆分项目集合，无则创建，有则添加
                if (project.IsSplit)
                {
                    BD_ProjectSplit_Detail spDetail = new BD_ProjectSplit_Detail();
                    spDetail.ProjectID = project.ID;
                    BD_ProjectSplit_DAL spDal = new BD_ProjectSplit_DAL(_connectionStringName);
                    BD_ProjectSplit_Detail_DAL spDetailDal = new BD_ProjectSplit_Detail_DAL(_connectionStringName);
                    //根据项目代码得到所属拆分项目ID
                    string splitID = spDal.GetSplitIDByCode(project.Code);
                    if (string.IsNullOrEmpty(splitID))//未创建拆分项目
                    {
                        BD_ProjectSplit splitItem = new BD_ProjectSplit();
                        splitItem.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        splitItem.Name = "";
                        splitItem.Remark = "";
                        spDal.InsertEntity(splitItem, transaction);
                        spDetail.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        spDetail.SplitID = splitItem.ID;
                    }
                    else
                    {
                        spDetail.ID = Honestysoft.BaseLibrary.Common.Guid.GetGuid();
                        spDetail.SplitID = splitID;
                    }
                    spDetailDal.InsertEntity(spDetail, transaction);
                }
                if (project.AddInvesments != null && project.AddInvesments.Count > 0)
                {
                    foreach (BD_ProjectAddInvestment item in project.AddInvesments)
                    {
                        item.ProjectID = project.ID;
                    }
                    project.AddInvesments = project.AddInvesments.FindAll((BD_ProjectAddInvestment find) => find.dataState != EnumItem.DataState.Delete);
                    if (project.AddInvesments != null && project.AddInvesments.Count > 0)
                    {
                        dal2.InsertEntitys(project.AddInvesments, transaction);
                    }
                }
                if (project.Budgets != null && project.Budgets.Count > 0)
                {
                    foreach (BD_ProjectBudget item in project.Budgets)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal3.InsertEntitys(project.Budgets, transaction);
                }
                if (project.GKLoanAmounts != null && project.GKLoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectGKLoanAmount item in project.GKLoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal4.InsertEntitys(project.GKLoanAmounts, transaction);
                }
                if (project.YearPlans != null && project.YearPlans.Count > 0)
                {
                    foreach (BD_ProjectInvestmentPlan item in project.YearPlans)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal5.InsertEntitys(project.YearPlans, transaction);
                }
                if (project.LoanAmounts != null && project.LoanAmounts.Count > 0)
                {
                    foreach (BD_ProjectLoanAmount item in project.LoanAmounts)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal6.InsertEntitys(project.LoanAmounts, transaction);
                }
                if (project.Companys != null && project.Companys.Count > 0)
                {
                    foreach (BD_ProjectCompany item in project.Companys)
                    {
                        item.ProjectID = project.ID;
                    }
                    dal8.InsertEntitys(project.Companys, transaction);
                }
                Bu_DocReceive_Temp_DAL dal7 = new Bu_DocReceive_Temp_DAL(_connectionStringName);
                Bu_DocReceive_Temp docRec = dal7.SelectEntityByKey(docRecID, transaction);                
                //查出当前相同项目下的新增合同，给予合同编码
                QueryParameters query = new QueryParameters();
                query.Add("ProjectCode", docRec.ProjectCode, QueryParameters.OperatorType.Equal);
                OrderParameters order = new OrderParameters();
                order.Add("ReceiveDate");
                List<Bu_DocReceive_Temp> lsTemp = dal7.SelectEntitys(query, order, transaction);
                if (lsTemp != null && lsTemp.Count > 0)
                {
                    for (int i = 0; i < lsTemp.Count; i++)
                    {
                        lsTemp[i].ContractCode = project.FCode + "-C" + (i + 1).ToString().PadLeft(3, '0');
                        lsTemp[i].ProjectID = project.ID;
                        lsTemp[i].IsToDBProj = true;
                    }
                    dal7.UpdateEntitys(lsTemp, transaction);
                }
                bRet = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return bRet;
        }

        /// <summary>
        /// 得到动态拆分项目的信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public BD_Project GetDymSplitProjectByCode(string code)
        {
            BD_Project project =  new BD_Project_DAL(_connectionStringName).GetDymSplitProjectByCode(code);
            if (project != null)
            {
                return GetFullProject(project.ID);
            }
            return null;
        }

        /// <summary>
        /// 查找项目简介
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="category"></param>
        /// <param name="name"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable QueryProjectOverview(string sn, string category, string name, int pageSize, int currentPageIndex,out int pageCount, out int recordCount)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectOverview(sn, category, name, pageSize, currentPageIndex,out pageCount, out recordCount);
        }

        /// <summary>
        /// 得到项目贷款额度
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="year"></param>
        /// <returns></returns>
        public decimal GetProjectLoanAmount(string projectId, int year)
        {
            return new BD_ProjectLoanAmount_DAL(_connectionStringName).GetProjectLoanAmount(projectId, year);
        }

        #region 现场考察
        /// <summary>
        /// 得到现场考察
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="name"></param>
        /// <param name="date"></param>
        /// <param name="pageSize"></param>
        /// <param name="currentPageIndex"></param>
        /// <param name="pageCount"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public DataTable GetInvestigateList(string sn, string name, DateTime? startDate,DateTime? endDate, int pageSize, int currentPageIndex, out int pageCount, out int recordCount)
        {
            return new Bu_Investigate_DAL(_connectionStringName).GetInvestigateList(sn, name, startDate,endDate, pageSize, currentPageIndex, out pageCount, out recordCount);
        }
        /// <summary>
        /// 得到项目的最后考察日期
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public DateTime? GetMaxInvDateByProject(string projectId)
        {
            return new Bu_Investigate_DAL(_connectionStringName).GetMaxInvDateByProject(projectId);
        }

        /// <summary>
        /// 得到最后的考察报告
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public Bu_Investigate GetMaxInvestigateByProject(string projectId)
        {
            return new Bu_Investigate_DAL(_connectionStringName).GetMaxInvestigateByProject(projectId);
        }
        #endregion
        /// <summary>
        /// 得到项目文档的是否属性
        /// </summary>
        /// <param name="projectSN"></param>
        /// <returns></returns>
        public DataTable GetProjectDocumentStatusBySN(string projectSN)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectDocumentStatusBySN(projectSN);
        }
        /// <summary>
        /// 得到项目文档的是否属性
        /// </summary>
        /// <param name="projectCode"></param>
        /// <returns></returns>
        public DataTable GetProjectDocumentStatusByCode(string projectCode)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectDocumentStatusByCode(projectCode);
        }
        /// <summary>
        /// 得到项目文档的是否属性
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public DataTable GetProjectDocumentStatusByID(string projectId)
        {
            return new BD_Project_DAL(_connectionStringName).GetProjectDocumentStatusByID(projectId);
        }
    }
}
